#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 08 03 01 06 00 01 65 6E
// 01 03 00 1A 00 72 E4 28

char err = 0;

unsigned short xCheckModbus(unsigned char *ptr, unsigned short len)
{
	unsigned char i;
	unsigned char chk;
	unsigned short crc;
	crc = 0xffff;
	for (; len; len--)
	{
		crc ^= *ptr;
		for (i = 8; i; i--)
		{
			chk = crc & 1;
			crc >>= 1;
			if (chk == 1)
				crc ^= 0xa001;
		}
		ptr++;
	}
	return ((crc << 8) | (crc >> 8));
}

unsigned char xCombineHex(const char *ptr1, const char *ptr2)
{
	unsigned char a, b;
	if ((*ptr1 >= '0') && (*ptr1 <= '9'))
		a = (*ptr1 - '0') * 16;
	else if ((*ptr1 >= 'A') && (*ptr1 <= 'F'))
		a = (*ptr1 - 'A' + 10) * 16;
	else if ((*ptr1 >= 'a') && (*ptr1 <= 'f'))
		a = (*ptr1 - 'a' + 10) * 16;
	else
		err = 2;

	if ((*ptr2 >= '0') && (*ptr2 <= '9'))
		b = (*ptr2 - '0');
	else if ((*ptr2 >= 'A') && (*ptr2 <= 'F'))
		b = (*ptr2 - 'A' + 10);
	else if ((*ptr2 >= 'a') && (*ptr2 <= 'f'))
		b = (*ptr2 - 'a' + 10);
	else
		err = 2;

	return a + b;
}

int main()
{
	// unsigned char arr[6] = {0x01, 0x03, 0x00, 0x1A, 0x00, 0x72};
	// unsigned char arr2[2];
	unsigned short crc = 0;

	char buf[512];
	char *ptr1, *ptr2;
	
	int len = 0;
	int i;

	while (1)
	{
		err = 0;
		len = 0;
		ptr1 = buf;

		gets(buf);

		if (buf[0] == 0)
		{
			continue;
		}

		while (*ptr1 != 0)
		{
			if (*ptr1 != 0x20)
			{
				ptr2 = ptr1 + 1;
				while (*ptr2 == 0x20)
				{
					ptr2++;
				}
				if (*ptr2 != 0)
				{
					buf[len] = xCombineHex(ptr1, ptr2);
				}
				else
				{
					buf[len] = 0;
					puts("input str num err");
					err = 1;
				}
				if (err == 2)
				{
					puts("input str err");
				}
				ptr1 = ptr2;
				len++;
			}
			ptr1++;
		}
		buf[len] = 0;

		if (!err)
		{
			for (i = 0; i < len; i++)
				printf("%02X ", buf[i]&0xff);
			crc = xCheckModbus(buf, len);
			printf("%02X %02X\n", crc >> 8, (unsigned char)crc);
		}
	}
	// crc = xCheckModbus(arr, 6);
	// printf("%02X ", (unsigned char)crc);
	// printf("%02X\n", (unsigned char)(crc >> 8));
	// printf("%04X\n",crc);
	// *(unsigned short*)arr2 = crc;
	// printf("%02X %02X\n", arr2[0], arr2[1]);

	system("pause");
	return 0;
}